import deviceManager from '@ohos.distributedHardware.deviceManager';
import { initInfo, initDebug } from './log';
import { objType } from './utils'

const TAG = "devicemanagerkit_js-ets"
let log = initInfo(TAG);
let debugLog = initDebug(TAG);

//let defDeviceList = [
//    {
//        deviceId: 'fgdhskjafkjds',
//        deviceName: '测试设备1',
//        deviceType: 0,
//        networkId: '123',
//        range: 1,
//        deviceState: 1,
//        isInAuth: false, // 是否正在可信认证
//        isTrust: false, // 是否可信
//        trustDeviceId: 'fgdhskjafkjds', // 可信设备id
//        transferLoading: false, // 是否流转中
//        isInTransfer: false, // 是否流转中
//        action: 2, // 可信设备状态 0在线， 1：设备已OK 2:设备已离线
//        updateTime: 123, // 最后一次更新时间
//        pinToken: 1,
//        isDelete: false
//    },
//    {
//        deviceId: 'fgdhskjafkjds111',
//        deviceName: '测试设备2',
//        deviceType: 0,
//        networkId: '123',
//        range: 1,
//        deviceState: 1,
//        isInAuth: false, // 是否正在可信认证
//        isTrust: false, // 是否可信
//        trustDeviceId: 'fgdhskjafkjds111', // 可信设备id
//        transferLoading: false, // 是否流转中
//        isInTransfer: false, // 是否流转中
//        action: 2, // 可信设备状态 0在线， 1：设备已OK 2:设备已离线
//        updateTime: 123, // 最后一次更新时间
//        pinToken: 1,
//        isDelete: false
//    },
//    {
//        deviceId: 'fgdhskjafkjds222',
//        deviceName: '测试设备3',
//        deviceType: 0,
//        networkId: '123',
//        range: 1,
//        deviceState: 1,
//        isInAuth: false, // 是否正在可信认证
//        isTrust: false, // 是否可信
//        trustDeviceId: 'fgdhskjafkjds222', // 可信设备id
//        transferLoading: false, // 是否流转中
//        isInTransfer: false, // 是否流转中
//        action: 2, // 可信设备状态 0在线， 1：设备已OK 2:设备已离线
//        updateTime: 123, // 最后一次更新时间
//        pinToken: 1,
//        isDelete: false
//    },
//    {
//        deviceId: 'fgdhskjafkjds333',
//        deviceName: '测试设备4',
//        deviceType: 0,
//        networkId: '123',
//        range: 1,
//        deviceState: 1,
//        isInAuth: false, // 是否正在可信认证
//        isTrust: false, // 是否可信
//        trustDeviceId: 'fgdhskjafkjds333', // 可信设备id
//        transferLoading: false, // 是否流转中
//        isInTransfer: false, // 是否流转中
//        action: 2, // 可信设备状态 0在线， 1：设备已OK 2:设备已离线
//        updateTime: 123, // 最后一次更新时间
//        pinToken: 1,
//        isDelete: false
//    }
//]


let DeviceStateObj = {
    '1': {
        loading: false,
        msg: '点击进行设备互信'
    },
    '2': {
        loading: true,
        msg: '设备互信中...'
    },
    '3': {
        loading: false,
        msg: '在线，点击进行视频流转'
    },
    '4': {
        loading: false,
        msg: '离线，等待对端设备上线'
    },
    '5': {
        loading: true,
        msg: '启动视频流转中...'
    },
    '6': {
        loading: false,
        msg: '视频流转中，点击停止'
    },
    '7':  {
        loading: false,
        msg: '停止视频流转中...'
    }
}

const BUNDLE_NAME = 'com.ohos.demandplayer';

export interface DeviceInfo {
    deviceId: string;
    deviceName: string;
    deviceType: DeviceType;
    networkId: string;
    range: number;
}

export enum DeviceType {
    UNKNOWN_TYPE = 0,
    SPEAKER = 0x0A,
    PHONE = 0x0E,
    TABLET = 0x11,
    WEARABLE = 0x6D,
    CAR = 0x83,
    TV = 0x9C
}

enum DeviceStateChangeAction {
    ONLINE = 0,
    READY = 1,
    OFFLINE = 2,
    CHANGE = 3
}

export interface DistributedManagerDeviceInfo {
    deviceId: string;
    deviceName: string;
    deviceType: DeviceType;
    networkId: string;
    range: number;
    deviceState: any;
    isInAuth: boolean; // 是否正在可信认证
    isTrust?: boolean; // 是否可信
    trustDeviceId: string; // 可信设备id
    transferLoading: boolean; // 是否流转中
    isInTransfer: boolean; // 是否流转中
    action:DeviceStateChangeAction; // 可信设备状态 0在线， 1：设备已OK 2:设备已离线
    updateTime:number; // 最后一次更新时间

    pinToken: number;

    isDelete: boolean;

}

export class DistributedManager {
    private static instance: DistributedManager | null; // 单例对象

    deviceManager: deviceManager.DeviceManager | null;
    subscribeId: number;
    publishId: number;

    findingChange: any;
    deviceList: Array<DistributedManagerDeviceInfo> | null; // 设备列表
    deviceListChange: (data: Array<DistributedManagerDeviceInfo>) => void;

    trustIdList: Array<string>; // 可信设备ID列表
    trustDeviceMap: { [key: string]: DistributedManagerDeviceInfo }; // 设备对象列表

    deviceIdList: Array<string>; // 设备ID列表
    deviceMap: { [key: string]: DistributedManagerDeviceInfo }; // 设备对象列表

    localDeviceInfo:DeviceInfo | null;

    findingInterval: any | null;
    findingTrustInterval: any | null;

    onFoundInterval: any | null;


    private constructor(){
        this.subscribeId = this.getSubscribeId();
        this.publishId = this.getPublishId();
        this.findingChange = null;
        this.localDeviceInfo = null;
        this.deviceList = [];

        this.trustIdList = [];
        this.trustDeviceMap = {};

        this.deviceIdList = [];
        this.deviceMap = {};


        this.createDeviceManager()
    }
    static getInstance(): DistributedManager {
        if (DistributedManager.instance == null) {
            DistributedManager.instance = new DistributedManager();
        }
        return DistributedManager.instance;
    }

    // SubscribeId
    getSubscribeId(){
//        let subscribeId =  Math.floor(Math.random() * 10000 + 1000);
//        if(subscribeId && this.subscribeId != subscribeId && this.publishId != subscribeId){
//            this.subscribeId = subscribeId;
//            return this.subscribeId;
//        } else {
//            return this.getSubscribeId();
//        }
        return 16251;
    }

    // publishId
    getPublishId(){
//        let publishId =  Math.floor(Math.random() * 10000 + 1000);
//        if(publishId && this.subscribeId != publishId && this.publishId != publishId){
//            this.publishId = publishId;
//            return this.publishId;
//        } else {
//            return this.getPublishId();
//        }
        return 16252;
    }


    // 创建设备管理器
    createDeviceManager(){
        log(`createDeviceManager IN`);
        try {
            deviceManager.createDeviceManager(BUNDLE_NAME, (err, data) => {
                if (err) {
                    debugLog("createDeviceManager error! errCode:" + err.code + ",errMessage:" + err.message + ",errData:" + JSON.stringify(err.data));
                    return;
                }
                this.deviceManager = data;
//                log(`createDeviceManager success`);
                this.getLocalDeviceInfo();
                this.stopDeviceDiscovery();
                this.unPublishDeviceDiscovery();
                this.onServiceDie();
                this.onDeviceFound();
                this.onDiscoverFail();
                this.onDeviceStateChange();
                this.getTrustedDeviceList();

            });
        } catch(err) {
            debugLog("createDeviceManager try catch! errCode:" + err.code + ",errMessage:" + err.message);
        }
    }

    // 获取本地设备信息
    getLocalDeviceInfo(){
        log(`getLocalDeviceInfo IN`);
        try {
            this.deviceManager.getLocalDeviceInfo((err, data) => {
                if (err) {
                    debugLog("getLocalDeviceInfo error! errCode:" + err.code + ",errMessage:" + err.message + ",errData:" + JSON.stringify(err.data));
                    return;
                }
                log('getLocalDeviceInfo: ' + JSON.stringify(data));
                if(data && data.deviceId){
                    this.localDeviceInfo = data;
                }
            })
        } catch (err) {
            debugLog("getLocalDeviceInfo try catch errCode:" + err.code + ",errMessage:" + err.message);
        }
    }

    // 注册发现设备回调监听。
    onDeviceFound(){
//        log(`onDeviceFound IN`);
        // 注册发现设备回调监听
        try {
            this.deviceManager.on('deviceFound', (data) => {
                log("onDeviceFound callback:" + JSON.stringify(data));
                if(data && data.device && data.device.deviceId){
                    let updateTime = new Date().getTime()
                    if(!this.deviceMap[data.device.deviceId]){
                        let device:DistributedManagerDeviceInfo = {
                            deviceId: data.device.deviceId,
                            deviceName: data.device.deviceName,
                            deviceType: data.device.deviceType,
                            networkId: data.device.networkId,
                            range: data.device.range,
                            isInAuth: false,
                            isTrust: false,
                            trustDeviceId: "",
                            transferLoading: false,
                            isInTransfer: false,
                            deviceState: DeviceStateObj['1'],
                            action: DeviceStateChangeAction.READY,
                            updateTime: updateTime,
                            pinToken: -1,
                            isDelete: false,
                        };
                        this.addDevice(data.device.deviceId, device);
                    } else {
                        this.updateDeviceProp(data.device.deviceId, 'updateTime', updateTime);
                    }
                    if(this.onFoundInterval){
                        clearInterval(this.onFoundInterval)
                    }
                    this.onFoundInterval = setTimeout(()=>{
                        this.updateDeviceIdList();
                    }, 200)
                }
            });
//            log(`onDeviceFound success`);
        } catch (err) {
            debugLog("onDeviceFound try catch errCode:" + err.code + ",errMessage:" + err.message);
        }
    }

    offDeviceFound(){
//        log(`offDeviceFound IN`);
        try {
            this.deviceManager.off('deviceFound');
//            log(`offDeviceFound success`);
        } catch (err) {
            debugLog("offDeviceFound try catch errCode:" + err.code + ",errMessage:" + err.message);
        }
    }

    // 注册设备发现失败回调监听。
    onDiscoverFail() {
//        log(`onDiscoverFail IN`);
        try {
            this.deviceManager.on('discoverFail', (data) => {
                log("onDiscoverFail callback:" + JSON.stringify(data));
            });
//            log(`onDiscoverFail success`);
        } catch (err) {
            debugLog("onDiscoverFail try catch errCode:" + err.code + ",errMessage:" + err.message);
        }
    }

    offDiscoverFail() {
//        log(`offDiscoverFail IN`);
        try {
            this.deviceManager.off('discoverFail');
//            log(`offDiscoverFail success`);
        } catch (err) {
            debugLog("offDiscoverFail try catch errCode:" + err.code + ",errMessage:" + err.message);
        }
    }

    onPublishSuccess(){
//        log(`onPublishSuccess IN`);
        try {
            this.deviceManager.on('publishSuccess', (data) => {
                log("onPublishSuccess callback:" + JSON.stringify(data));
            });
//            log(`onPublishSuccess success`);
        } catch (err) {
            debugLog("onPublishSuccess try catch errCode:" + err.code + ",errMessage:" + err.message);
        }
    }

    offPublishSuccess(){
//        log(`offPublishSuccess IN`);
        try {
            this.deviceManager.off('publishSuccess');
//            log(`offPublishSuccess success`);
        } catch (err) {
            debugLog("offPublishSuccess errCode:" + err.code + ",errMessage:" + err.message);
        }
    }

    onPublishFail(){
//        log(`onPublishFail IN`);
        try {
            this.deviceManager.on('publishFail', (data) => {
                log("onPublishFail callback:" + JSON.stringify(data));
            });
//            log(`onPublishFail success`);
        } catch (err) {
            debugLog("publishFail try catch errCode:" + err.code + ",errMessage:" + err.message);
        }

    }

    offPublishFail(){
//        log(`offPublishFail IN`);
        try {
            this.deviceManager.off('publishFail');
//            log(`offPublishFail success`);
        } catch (err) {
            debugLog("offPublishFail try catch errCode:" + err.code + ",errMessage:" + err.message);
        }
    }

    onServiceDie(){
//        log(`onServiceDie IN`);
        try {
            this.deviceManager.on("serviceDie", () => {
                log("serviceDie callback");
            });
//            log(`onServiceDie success`);
        } catch (err) {
            debugLog("serviceDie try catch errCode:" + err.code + ",errMessage:" + err.message);
        }
    }

    offServiceDie(){
//        log(`offServiceDie IN`);
        try {
            this.deviceManager.off('serviceDie');
//            log(`offServiceDie success`);
        } catch (err) {
            debugLog("offServiceDie errCode:" + err.code + ",errMessage:" + err.message);
        }
    }

    // 监听设备状态改变回调
    onDeviceStateChange(){
//        log(`onDeviceStateChange IN`);
        try {
            this.deviceManager.on('deviceStateChange', (data) => {
//                log("deviceStateChange on:" + JSON.stringify(data));
                if(data){
                    let trustDeviceId = data.device.deviceId;
                    let deviceId = trustDeviceId;
                    let action = data.action;
                    let time = new Date().getTime();

                    if(this.trustDeviceMap[trustDeviceId]){
                        deviceId = this.trustDeviceMap[trustDeviceId].deviceId
                        this.updateDeviceProp(deviceId, 'action', action);
                        this.updateDeviceProp(deviceId, 'updateTime', time);
                    } else {
                        let isInAuth = false;
                        let isInAuthId = "";
                        let isInAuthName = ""
                        let isInAuthType:DeviceType = DeviceType.UNKNOWN_TYPE;
                        for(let i=0;i<this.deviceIdList.length;i++){
                            let id = this.deviceIdList[i];
                            if(this.deviceMap[id] && this.deviceMap[id].isInAuth){
                                isInAuth = true;
                                isInAuthId = id;
                                isInAuthName = this.deviceMap[id].deviceName;
                                isInAuthType = this.deviceMap[id].deviceType;
                            }
                        }

                        let trustDevice:DistributedManagerDeviceInfo = {
                            deviceId: deviceId,
                            deviceName: data.device.deviceName,
                            deviceType: data.device.deviceType,
                            networkId: data.device.networkId,
                            range: data.device.range,
                            isInAuth: false,
                            isTrust: true,
                            trustDeviceId: trustDeviceId,
                            transferLoading: false,
                            isInTransfer: false,
                            deviceState: DeviceStateObj['3'],
                            action: DeviceStateChangeAction.READY,
                            updateTime: time,
                            pinToken: -1,
                            isDelete: false,
                        };
                        if(isInAuthId && isInAuth && isInAuthName==data.device.deviceName && isInAuthType==data.device.deviceType){
                            trustDevice.deviceId = isInAuthId;
                            this.updateDeviceProp(isInAuthId, 'trustDeviceId', trustDeviceId);
                            this.updateDeviceProp(isInAuthId, 'isInAuth', false);
                            this.updateDeviceProp(isInAuthId, 'isTrust', true);
                        } else {
                            this.addDevice(trustDeviceId,trustDevice);
                        }
                        this.addTrustDevice(trustDeviceId,trustDevice);
                    }
                    this.updateDeviceIdList();
                }
            });
        } catch (err) {
            debugLog("deviceStateChange try catch errCode:" + err.code + ",errMessage:" + err.message);
        }
    }

    offDeviceStateChange(){
//        log(`offDeviceStateChange IN`);
        try {
            this.deviceManager.off('deviceStateChange');
//            log(`offDeviceStateChange success`);
        } catch (err) {
            debugLog("offDeviceStateChange errCode:" + err.code + ",errMessage:" + err.message);
        }
    }

    offAllEvents(){
        this.stopDeviceDiscovery();
        this.offDeviceFound();
        this.offDiscoverFail();
        this.offDeviceStateChange();
        this.offServiceDie();
    }


    // 开始扫描
    startScan(){
        this.stopScan();
        this.findingInterval = setInterval(()=>{
            this.startDeviceDiscovery();
            this.getTrustedDeviceList();
        }, 5000)
    }

    // 结束扫描
    stopScan(){
        if(this.onFoundInterval){
            clearInterval(this.onFoundInterval)
            this.onFoundInterval = null;
        }
        if(this.findingInterval){
            clearInterval(this.findingInterval);
            this.findingInterval = null;
        }
    }

    // 开始发现周边设备
    startDeviceDiscovery(){
//        log("startDeviceDiscovery IN");
        // 生成发现标识，随机数确保每次调用发现接口的标识不一致
        this.getSubscribeId();
        let subscribeInfo: deviceManager.SubscribeInfo = {
            "subscribeId": this.subscribeId,
            "mode": deviceManager.DiscoverMode.DISCOVER_MODE_ACTIVE, // 主动模式
            "medium": deviceManager.ExchangeMedium.COAP,  // 自动发现类型，同时支持多种发现类型
            "freq": deviceManager.ExchangeFreq.HIGH,    // 高频率
            "isSameAccount": false,
            "isWakeRemote": true,
            "capability": 1
        };
        // 过滤设备
//        let filterOptions = {
//            "filter_op": "OR", // 可选, 默认"OR"
//            "filters": [
//                {
//                    "type": "range",
//                    "value": 50 // 需过滤发现设备的距离，单位(cm)
//                }
//            ]
//        };
//        this.deviceManager.startDeviceDiscovery(subscribeInfo, JSON.stringify(filterOptions));
        try {
            this.deviceManager.startDeviceDiscovery(subscribeInfo);
//            log("startDeviceDiscovery success");
            setTimeout(()=>{
                this.stopDeviceDiscovery();
            }, 4000)
        } catch (err) {
            debugLog("startDeviceDiscovery try catch errCode:" + err.code + ",errMessage:" + err.message);
        }
    }

    // 停止发现周边设备
    stopDeviceDiscovery(){
//        log("stopDeviceDiscovery IN");
        try {
            // stopDeviceDiscovery和startDeviceDiscovery需配对使用，入参需要和startDeviceDiscovery接口传入的subscribeId值相等
            this.deviceManager.stopDeviceDiscovery(this.subscribeId);
//            log("stopDeviceDiscovery success");
        } catch (err) {
            debugLog("stopDeviceDiscovery try catch errCode:" + err.code + ",errMessage:" + err.message);
        }
    }

    // 获取可信设备列表
    getTrustedDeviceList(){
        try {
            this.deviceManager.getTrustedDeviceList((err, data) => {
                if (err) {
                    debugLog("getTrustedDeviceList errCode:" + err.code + ",errMessage:" + err.message);
                    return;
                }
//                log('get trusted device info: ' + JSON.stringify(data));
                if(data && data.length > 0) {
                    let time = new Date().getTime();
                    data.forEach((d) => {
                        if (d && d.deviceId) {
                            let trustDeviceId = d.deviceId;
                            let deviceId = trustDeviceId;
                            if(this.trustDeviceMap[trustDeviceId]){
                                deviceId = this.trustDeviceMap[trustDeviceId].deviceId;
                                this.updateDeviceProp(deviceId, 'updateTime', time);
                            } else {
                                // ???
                                let isInAuth = false;
                                let isInAuthId = "";
                                let isInAuthName = ""
                                let isInAuthType:DeviceType = DeviceType.UNKNOWN_TYPE;
                                for(let i=0;i<this.deviceIdList.length;i++){
                                    let id = this.deviceIdList[i];
                                    if(this.deviceMap[id] && this.deviceMap[id].isInAuth){
                                        isInAuth = true;
                                        isInAuthId = id;
                                        isInAuthName = this.deviceMap[id].deviceName;
                                        isInAuthType = this.deviceMap[id].deviceType;
                                    }
                                }

                                let trustDevice:DistributedManagerDeviceInfo = {
                                    deviceId: deviceId,
                                    deviceName: d.deviceName,
                                    deviceType: d.deviceType,
                                    networkId: d.networkId,
                                    range: d.range,
                                    isInAuth: false,
                                    isTrust: true,
                                    trustDeviceId: trustDeviceId,
                                    transferLoading: false,
                                    isInTransfer: false,
                                    deviceState: DeviceStateObj['3'],
                                    action: DeviceStateChangeAction.READY,
                                    updateTime: time,
                                    pinToken: -1,
                                    isDelete: false,
                                };
                                if(isInAuthId && isInAuth && isInAuthName==d.deviceName && isInAuthType==d.deviceType){
                                    trustDevice.deviceId = isInAuthId;
                                    this.updateDeviceProp(isInAuthId, 'trustDeviceId', trustDeviceId);
                                    this.updateDeviceProp(isInAuthId, 'isInAuth', false);
                                    this.updateDeviceProp(isInAuthId, 'isTrust', true);
                                } else {
                                    this.addDevice(trustDeviceId,trustDevice);
                                }
                                this.addTrustDevice(trustDeviceId,trustDevice);
                            }
                        }
                    });
                }
                this.updateDeviceIdList();
            });
        } catch (err) {
            debugLog("getTrustedDeviceList errCode:" + err.code + ",errMessage:" + err.message);
        }
    }
    // 发布设备
    publishDeviceDiscovery(){
//        log("publishDeviceDiscovery IN");
        this.getPublishId();
        var publishInfo: deviceManager.PublishInfo = {
            "publishId": this.publishId,
            "mode": 0x55, // 主动模式
            "freq": 2,    // 高频率
            "ranging": true  // 支持发现时测距
        };
        try {
            this.deviceManager.publishDeviceDiscovery(publishInfo); // 当有发布结果时，通过回调通知给应用程序
//            log("publishDeviceDiscovery success");
        } catch (err) {
            debugLog("publishDeviceDiscovery try catch errCode:" + err.code + ",errMessage:" + err.message);
        }
    }

    unPublishDeviceDiscovery(){
//        log("unPublishDeviceDiscovery IN");
        try {
            // unPublishDeviceDiscovery和publishDeviceDiscovery配对使用，入参需要和publishDeviceDiscovery接口传入的publishId值相等
            this.deviceManager.unPublishDeviceDiscovery(this.publishId);
//            log("unPublishDeviceDiscovery success");
        } catch (err) {
            debugLog("unPublishDeviceDiscovery try catch errCode:" + err.code + ",errMessage:" + err.message);
        }
    }

    // 认证设备
    authenticateDevice(deviceInfo, authParam ) {
//        log("authenticateDevice In");

        // 认证的设备信息，可以从发现的结果中获取
        //        var deviceInfo ={
        //          "deviceId": "XXXXXXXX",
        //          "deviceName": "",
        //          deviceType: 0x0E
        //        };
        //        let authParam = {
        //          "authType": 1, // 认证类型： 1 - 无账号PIN码认证
        //          "extraInfo": {}
        //        }
        let deviceId = deviceInfo.deviceId;
        let device:DistributedManagerDeviceInfo = this.deviceMap[deviceId];
        device.isInAuth = true;
//        update
        try {
//            log("authenticateDevice deviceInfo:" + JSON.stringify(deviceInfo));
//            log("authenticateDevice authParam:" + JSON.stringify(authParam));
            this.deviceManager.authenticateDevice(deviceInfo, authParam, (err, data) => {
//                log("authenticateDevice result err:" + JSON.stringify(err));
//                log("authenticateDevice result data:" + JSON.stringify(data));
                if (err) {
                    debugLog("authenticateDevice errCode:" + err.code + ",errMessage:" + err.message);
                    device.isInAuth = false;
                    this.updateDeviceIdList();
                    //        update
                    return;
                }

                if(data && data.deviceId){
//                    let trustDeviceId = data.deviceId;
//                    let pinToken = data.pinToken;
//                    device.trustDeviceId = trustDeviceId;
                    device.pinToken = data.pinToken;
                    device.updateTime = new Date().getTime();
                }
//                this.getTrustedDeviceList();
//                this.updateDeviceIdList();
            });
        } catch (err) {
            debugLog("authenticateDevice try catch errCode:" + err.code + ",errMessage:" + err.message);
        }
    }
    // 解除认证的设备
    unAuthenticateDevice(deviceInfo) {
//        log("unAuthenticateDevice In");
        let deviceId = deviceInfo.deviceId;
        let device:DistributedManagerDeviceInfo = this.deviceMap[deviceId];
        device.isInAuth = true;
        try {
//            log("unAuthenticateDevice deviceInfo:" + JSON.stringify(deviceInfo));
            let trustDevice = {
                deviceId: device.trustDeviceId,
                deviceName: device.deviceName,
                deviceType: device.deviceType,
                networkId: device.networkId,
                range: device.range,
                authForm:0
            }
            this.deviceManager.unAuthenticateDevice(trustDevice);
            this.trustDeviceMap[device.trustDeviceId] = null;
            if(deviceId == device.trustDeviceId){
                this.deviceMap[deviceId] = null;
            } else {
                device.isInAuth = false;
                device.networkId = "";
                device.isTrust = false;
                device.trustDeviceId = "";
                device.isInTransfer = false;
                device.action = DeviceStateChangeAction.READY;
                device.updateTime = new Date().getTime();
                device.pinToken = -1;
                device.isDelete = false;
            }
//            this.getTrustedDeviceList(); // 获取可信设备列表
        } catch (err) {
            debugLog("authenticateDevice try catch errCode:" + err.code + ",errMessage:" + err.message);
        }
    }


    addDevice(deviceId:string, data:DistributedManagerDeviceInfo){
        this.deviceIdList.push(deviceId);
        this.deviceMap[deviceId] = data;
    }

    addTrustDevice(deviceId:string, data:DistributedManagerDeviceInfo){
        this.trustIdList.push(deviceId);
        this.trustDeviceMap[deviceId] = data;
    }

    // 更新设备
    updateDeviceIdList(){
        let deviceList = [];
        let time = new Date().getTime();
        let sp = 1000 * 60 * 1;
        this.deviceIdList.forEach((id,i)=>{
            let device = this.deviceMap[id];
            if(this.deviceMap[id]){
                let overTime = time - this.deviceMap[id].updateTime;
                if(overTime < sp) {
                    deviceList.push(device);
                }
            }
        });
        this.deviceList = deviceList;
        if("function" == objType(this.deviceListChange)){
            this.deviceListChange(deviceList)
        }
    }

    updateDeviceProp(deviceId, key, value){
        let device = this.deviceMap[deviceId];
        if(device){
            device[key] = value;
            let trustDeviceId = this.deviceMap[deviceId].trustDeviceId;
            if(this.trustDeviceMap[trustDeviceId]){
                this.trustDeviceMap[trustDeviceId][key] = value;
            }
        }
    }

    // 删除设备
    deleteDeviceId(deviceId:string, newId?:string){
        let ind = this.deviceIdList.indexOf(deviceId);
        if(ind > -1){
//            if(newId){
//                this.deviceIdList.splice(ind, 0, newId)
//            }
            if(this.deviceMap[deviceId]){
                this.deviceMap[deviceId].isDelete = true;
            }
        }
    }

    // 绑定设备列表变化回调函数
    onDeviceListChange(callback:(data: Array<DistributedManagerDeviceInfo>) => void ){
        if("function" == objType(callback)){
            this.deviceListChange = callback;
        }
    }

    // 释放设备管理器
    release(){
        try {
            this.stopScan();
            this.offAllEvents();
            this.deviceManager.release();
        } catch (err) {
            console.error("release try catch errCode:" + err.code + ",errMessage:" + err.message);
        }
    }
}
